﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AD.Contract;
using AD.IBLL;
using AD.Contract.Models;
using AD.DAL;
using HZT.Framework.Contract;
using HZT.Framework.Utility;


namespace AD.BLL
{
    public class DeptService : IDeptService
    {
        //获取部门列表
        public IEnumerable<Department> GetDeptList(CommonRequest request = null)
        {
            request = request ?? new CommonRequest();
            using (var dbContext = new ADDbContext())
            {
                IQueryable<Department> queryList = dbContext.Departments;
                if (!string.IsNullOrEmpty(request.Name))
                {
                    queryList = queryList.Where(c => c.Name.Contains(request.Name));
                }
                return queryList.OrderByDescending(u => u.Sort).ToPagedList(request.PageIndex, request.PageSize);
            }
        }
        //获取单个部门
        public Department GetDept(string Id)
        {
            if (string.IsNullOrEmpty(Id)) return new Department();
            using (var dbContext = new ADDbContext())
            {
                return dbContext.Departments.Where(u => u.Id == Id).SingleOrDefault();
            }
        }

        public void SaveDepartment(Department dept)
        {
            using (var dbContext = new ADDbContext())
            {
                if (!string.IsNullOrEmpty(dept.Id))
                {
                    dbContext.Update<Department>(dept);
                    //var roles = dbContext.Roles.Where(r => dept.RoleIds.Contains(r.ID)).ToList();
                    //dept.Roles = roles;
                    dbContext.SaveChanges();
                }
                else
                {
                    // var existUser = dbContext.FindAll<Department>(u => u.LoginName == dept.LoginName);
                    dept.Id = CommonFunction.GetNewID();
                    dbContext.Insert<Department>(dept); 
                    dbContext.SaveChanges();

                }
            }
        }

    }
}
